import 'package:demo_flutter_module/sec_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: {
        'test': (context) {
          return SecPage();
        },
      },
      home: HomeSelectPage(),
    );
  }
}

class HomeSelectPage extends StatefulWidget {
  @override
  _HomeSelectPageState createState() => _HomeSelectPageState();
}

class _HomeSelectPageState extends State<HomeSelectPage> {
  int _counter = 0;
  String _reciver = "";

  BasicMessageChannel _basicMessageChannel =
      BasicMessageChannel("101", StandardMessageCodec());

  @override
  void initState() {
    super.initState();
    _basicMessageChannel.setMessageHandler((message) async {
      print("flutter-$message");
      _reciver = message.toString();
      setState(() {});
      return "123";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("消息通信")),
      body: Container(
        width: double.infinity,
        padding: EdgeInsets.all(20),
        child: Column(
          children: [
            Text("当前计数 $_counter"),
            SizedBox(
              height: 30,
            ),
            Text("$_reciver"),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () async {
          _counter++;
          sendMessage();
          setState(() {});
        },
      ),
    );
  }

  void sendMessage() async {
    //发送消息
    var result = await _basicMessageChannel.send(_counter);
    print("发送消息成功 $result");
  }
}
